package com.zhbr.mvp.ui.activity;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.zhbr.common.HttpConstants;
import com.zhbr.common.StringUtils;
import com.zhbr.mvp.contract.LoginContract;
import com.zhbr.mvp.presenter.LoginPresenter;
import com.zhbr.R;
import com.zhbr.entity.Account;
import com.zhbr.mvp.base.view.BaseActivity;
import com.zhbr.ContextApplication;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View {


    @BindView(R.id.edit_username)
    EditText edit_username;
    @BindView(R.id.edit_password)
    EditText edit_password;



    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {

    }
    @Override
    protected void initData() {

    }


    @OnClick({R.id.button_login,R.id.button_register})
    public void onViewClicked(View view){
        switch (view.getId()){
            case R.id.button_login:
                String username = edit_username.getText().toString();
                String password= edit_password.getText().toString();
                if (StringUtils.isEmpty(username)){
                    showToast("用户名不能为空");
                    return;
                }
                if (StringUtils.isEmpty(password)){
                    showToast("密码不能为空");
                    return;
                }
                mPresenter.login(username,password);
                break;
            case R.id.button_register:
                navigateTo(RegisterActivity.class);
                break;

        }
    }



    @Override
    public void onLoginSuccess(Account data) {
        //登录成功回调
        Log.d("Info", "onLoginSuccess: 登录成功！");
        //利用密码字段传递token
        Log.d("token：",""+data.getActpassword());
        //保存token到数据库中
        ContextApplication.getInstance().saveString2SP("user_info","token",data.getActpassword());
        ContextApplication.getInstance().saveString2SP("user_info","nickname",data.getActnickname());
        ContextApplication.getInstance().saveString2SP("user_info","phone",data.getActtelephone());
        navigateTo(HomeActivity.class);
    }

    @Override
    public void onLoginFail(Throwable ex, String code, String msg) {
        Log.e("登录失败：", code);
        if(code.equals(HttpConstants.CODE_USERNAME_INVALID)){
            showToast("用户不存在");
        }else if (code.equals(HttpConstants.CODE_PASSWORD_INVALID)){
            showToast("密码错误");
         }

    }

    /**
     * 注意:
     * 登录页面按返回直接退到桌面，防止用户注销后按返回跳过登录
     */
    @Override
    public void onBackPressed() {
        //直接返回桌面
        Intent home=new Intent(Intent.ACTION_MAIN);
        home.addCategory(Intent.CATEGORY_HOME);
        startActivity(home);
    }
}
